﻿// Copyright (c) egmkang wang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.


namespace XServer.Grains
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Orleans;
    using Orleans.Concurrency;
    using GrainInterfaces;
    using XServer.SDK;
    //using SharpServer.Record;

    [Reentrant]
    public class PlayerIDGenGrain : Grain, IPlayerIDGrain
    {
        static OnceFlag once = new OnceFlag();
        static readonly string UID_KEY = String.Format("{0}_{1}", (int)UniqueIDType.UniqueID_PlayerID, 0);
        static IUniqueIDGrain uidGrain = null;

        public override Task OnActivateAsync()
        {
            once.CallOnce(() =>
            {
                uidGrain = this.GrainFactory.GetGrain<IUniqueIDGrain>(UID_KEY);
                var info = new UniqueIDInfo(UID_KEY, uidGrain);
                UniqueIDHelper.InitUniqueID(info);
            });
            return base.OnActivateAsync();
        }

        public async Task<KeyValuePair<long, long>> GetPlayerIDByOpenID(string openID, long serverID)
        {
            var result = await this.GetPlayerID(openID, serverID);
            long uid = result.Key;
            long create_time = result.Value;
            if (result.Key <= 0L)
            {
                uid = await UniqueIDHelper.GetNewID(UID_KEY);
            }
            if (create_time <= 0)
            {
                create_time = Platform.GetSeconds();
            }

            await this.UpdatePlayerLoginInfo(openID, serverID, uid, create_time);
            return new KeyValuePair<long, long>(uid, create_time);
        }

        async Task<KeyValuePair<long, long>> GetPlayerID(string openID, long serverID)
        {
            //var result = await CassandraClient.GetPlayerID(openID, serverID);
            //return result;
            //TODO:egmkang
            return new KeyValuePair<long, long>(1, 1);
        }

        async Task UpdatePlayerLoginInfo(string openID, long serverID, long playerID, long create_time)
        {
            //var result = await CassandraClient.UpdatePlayerID(openID, serverID, playerID, create_time, Platform.GetSeconds());
            await TaskDone.Done;
        }
    }
}
